package com.yp.infrastructure.common.annotation.aspect;


import com.yp.infrastructure.common.annotation.ElapsedTime;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * 监控方法运行时间, 在代码调试中使用.
 */
@Aspect
@Slf4j
@Component
public class ElapsedTimeAspect implements Ordered {

    @Override
    public int getOrder() {
        return 0;
    }

    private final AtomicInteger count = new AtomicInteger();


    @Pointcut(value = "@annotation(elapsedTime)", argNames = "elapsedTime")
    protected void setElapsedTime(ElapsedTime elapsedTime) {
    }

    @Around(value = "setElapsedTime(elapsedTime)", argNames = "joinPoint,elapsedTime")
    public Object currEventInterceptorAspect(ProceedingJoinPoint joinPoint,
                                             ElapsedTime elapsedTime) throws Throwable {
        long start = System.currentTimeMillis();
        Object o = null;
        try {
            o = joinPoint.proceed();
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            log.info("elapsed time: {}", System.currentTimeMillis() - start);
        }
        return o;
    }

    private boolean isCurrEvent(Instant instant, int interval) {
        if (null == instant) return true;
        Instant now = Instant.now();
        Instant event = instant.plus(interval, ChronoUnit.SECONDS);
        return event.isAfter(now);
    }
}
